<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\api;

use app\common\controller\ApiController;
use app\common\model\Aes;
use app\mill\model\Finance;
use think\App;
use app\mill\model\Give as GiveModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Address as AddressModel;
use app\wh\model\Color as ColorModel;
use app\wh\model\Stock as StockModel;
use app\admin\model\Config as ConfigModel;
use think\Db;

/**
 * 用户公开控制器
 * @package app\user\admin
 */
class Index extends ApiController
{
    public function __construct(App $app = null)
    {
        parent::__construct($app);

        $this->is_member();
    }

    /**
     * 监听
     */
    public function timer(){

        success('');
    }
    /**
     * 产品详情
     */
    public function detail(){
        // 获取参数
        $data = input('');

        $where[] = ['give_sn','=',$data['give_sn']];

        $give = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field("a.*,o.batch,g.status as give_status,g.give_sn,g.archives_sn,g.counter,concat(g.counter,'/',a.number) as number_str")
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->where($where)
            ->find();

        if(!empty($give['sort']))$give['sort'] = "{$give['sort']}-{$give['counter']}";
        $give['status_str'] = GiveModel::$give_status[$give['give_status']];

        success('操作成功',$give);
    }
    /**
     * 扫码更新产品进度
     * @return mixed
     */
    public function ableGive()
    {

        $role = GiveModel::$role;

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();

            $_log_time = time();
            $_log_i = 0;
            //file_put_contents('扫码.log',date('Y-m-d H:i:s',$_log_time)."  记数：{$_log_i}\r\n".json_encode($data,JSON_UNESCAPED_UNICODE)."\r\n\r\n",FILE_APPEND);

            //获取离线状态下的用户ID
            $archives_sn = !empty($data['archives_sn'])?$data['archives_sn']:'';
            $give_sn = explode(',',$data['give_sn']);
            $user_ids = !empty($data['uid'])?explode(',',$data['uid']):'';
            $car_ids = !empty($data['car_id'])?explode(',',$data['car_id']):'';
            $color_s = !empty($data['color'])?explode(',',$data['color']):'';
            $address_sn_s = !empty($data['address_sn'])?explode(',',$data['address_sn']):'';

            $user = $this->member;

            $data_list = [];
            if(!empty($give_sn)){
                $_log_str = '';
                foreach ($give_sn as $k=>$v){

                    $uid_arr = !empty($user_ids[$k])?$user_ids[$k]:$user['id'];
                    $uid_arr = explode('|',$uid_arr);//多人联合扫码，用“|”分隔，并按系统分配的比例工作量
                    $uid = $uid_arr[0];//默认第一个uid，为主扫码人
                    $car_id = !empty($car_ids[$k])?$car_ids[$k]:$car_ids;
                    $color = !empty($color_s[$k])?$color_s[$k]:$color_s;
                    $address_sn = !empty($address_sn_s[$k])?$address_sn_s[$k]:$address_sn_s;
                    $user = Db::name('admin_user')
                        ->alias('u')
                        ->field('u.*,u.id as uid,g.name as group_name,g.name as job_name')
                        //->leftJoin('admin_user_group g','g.id=u.group')
                        ->leftJoin('admin_user_job g','g.id=u.job')//不再显示部门，改成显示工位
                        ->where(['u.id'=>$uid])
                        ->find();

                    $where = [
                        ['g.give_sn','=',$v],
                    ];

                    if(empty(GiveModel::$role[$user['group']]['status'][0])){
                        $where = '1=2';
                        $msg = '该工位没有生产权限';
                    }
                    else $user['give_sort'] = GiveModel::$role[$user['group']]['status'][0];

                    //判断产品编号是否完整
                    if(strpos($v,'-') === false && 1==2){

                        //匹配批次
                        if(!empty($archives_sn)){
                            $where = [
                                ['g.give_sn','like',"%-{$v}"],
                                ['g.archives_sn','=',$archives_sn],
                            ];
                        }
                        else {
                            $where = '1=2';
                            $msg = '请选择批次';
                        }
                    }

                    //成功的提示
                    $msg_succ = '成功';

                    $give = Db::name('mill_order_archives_give')
                        ->alias('g')
                        ->field('g.*,g.status as give_status,a.one_area,a.model,a.part,a.sort as a_sort,o.mill_id,o.status as order_status,o.client_id,o.user_price_status,a.user_price_setting,o.give_scale,o.give_sort,o.quality_status as order_quality_status')//,o.give_sort
                        ->leftJoin('mill_order o','o.id=g.order_id')
                        ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                        ->where($where)
                        ->find();

                    if(!empty($give) && $give['order_status'] > 0){

                        //获取默认员工单价分配比例
                        if(empty($give['give_scale']))$give['give_scale'] = implode("\r\n",config('mill_give_scale'));

                        if(empty($give['user_price_setting'])){
                            //$user_price = [];
                            //foreach (config('mill_give_user_price_setting') as $uk=>$uv){
                            //    $uv_arr = explode('_',$uv);
                            //    $user_price[$uk]["price0"] = $uv_arr[0];
                            //    $user_price[$uk]["price1"] = $uv_arr[1];
                            //}
                            //$give['user_price_setting'] = json_encode($user_price);
                        }

                        // 验证权限
                        $msg = GiveModel::role($user,$give['status'],$give['give_sort']);
                        //验证该产品是否已取消生产
                        if($give['quality_status'] == -3)$msg = '该产品已取消生产';
                        //单独验证发货部是否禁止发货
                        if($give['address_status'] < 0 && $user['group'] == 8)$msg = '该产品禁止发货';
                        //匹配批次
                        if(empty($msg) && $archives_sn && !in_array($give['archives_sn'],explode(',',$archives_sn)))$msg = '批次不匹配';
                        //匹配折弯颜色
                        if(empty($msg) && $color){
                            $give_color = Db::name('mill_order_archives')->where(['id'=>$give['archives_id']])->value('color');
                            if($color != $give_color)$msg = '颜色不匹配';
                        }

                        //发货日志
                        if($user['group'] == 8)file_put_contents('扫码发货.log',date('Y-m-d H:i:s',$_log_time)."  档案号：{$give['archives_sn']}   编号：{$give['give_sn']}   扫码编号：{$v}\r\n".json_encode($data,JSON_UNESCAPED_UNICODE)."\r\n\r\n",FILE_APPEND);

                        //判断是否需要质检
                        $quality = [];//质检设置
                        if($give['order_quality_status'] == 1){
                            $quality_where = [
                                ['status','=',0],
                                ['order_id','=',$give['order_id']],
                                ['model','=',$give['model']],
                            ];
                            //质检设置
                            $quality = Db::name('mill_order_archives_quality_setting')->where($quality_where)->where([['give_status','=',$user['give_sort']]])->find();
                            //当前工艺是否首检：仅做语音提示
                            if(!empty($quality))$msg_succ .= "。[".GiveModel::$give_status[$user['give_sort']]."]工艺要首检";
                            //获取上个工艺未首检的状态
                            $quality_0 = Db::name('mill_order_archives_quality_setting')->where($quality_where)->where([['is_first','=',1],['give_status','<',$user['give_sort']]])->find();
                            //上个工艺是否首检：上个工艺未首检不让扫码
                            if(!empty($quality_0))$msg = "[".GiveModel::$give_status[$quality_0['give_status']]."]工艺未质检";
                        }
                        //质检问题的产品，需重新质检
                        //if($give['quality_status'] < 0)$msg = "因质量问题，[".GiveModel::$give_status[abs($give['status'])]."]工艺请重新质检";

                        if(empty($msg)){

                            //更新产品
                            $this->ableGiveUpdate($give,$user,$uid_arr,$quality,$car_id,$address_sn);

                        }

                        $give = Db::name('mill_order_archives_give')
                            ->alias('g')
                            ->field("a.*,o.batch,o.engineering,g.status as give_status,g.give_sn,g.archives_sn,g.counter,concat(g.counter,'/',a.number) as number_str")
                            ->leftJoin('mill_order o','o.id=g.order_id')
                            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                            ->where(['g.id'=>$give['id']])
                            ->find();
                    }
                    else{
                        if(empty($msg))$msg = '该产品不存在';
                        $give['give_sn'] = $v;

                    }

                    if(!empty($give['sort']))$give['sort'] = "{$give['sort']}-{$give['counter']}";
                    //1：成功 0：失败
                    $give['status_code'] = empty($msg)?1:0;
                    $give['nickname'] = $user['nickname'];
                    $give['group_name'] = $user['group_name'];
                    //提示状态
                    $give['code_str'] = '该产品不存在';
                    if(isset($give['give_status']))$give['code_str'] = GiveModel::$give_status[$give['give_status']];

                    $give['status_str'] = $msg?$msg:'已上传';
                    //成功的提示
                    $give['msg'] = $msg_succ;

                    $give['time_str'] = date('Y.m.d H:i');

                    $data_list[] = $give;

                    $_log_str .= "产品编号：{$give['give_sn']}  状态：{$give['status_str']}";
                }

                //file_put_contents('扫码reust.log',date('Y-m-d H:i:s',$_log_time)."  记数：{$_log_i}\r\n".$_log_str."\r\n\r\n",FILE_APPEND);

                success('操作成功',$data_list);
            }
            errors('操作失败');
        }

        errors('操作异常');
    }
    public function ableGiveUpdate($give_list = [],$user = [],$uid_arr = [],$quality = [],$car_id = '',$address_sn = ''){

        $role = GiveModel::$role;
        $give_list = [$give_list];

        //从复合开始，往后的扫码，都要同步更新正板或背板状态
        $tb_status = GiveModel::$role[12]['status'][0];//复合状态
        $last_status = GiveModel::$role[$user['group']]['status'][0];//用户可扫码的状态

        //复合、发货扫码，同步更新正板或背板状态
        if($last_status >= $tb_status){

            $a_sort = $give_list[0]['a_sort'];

            //背板（带“#”），去掉“#”就是正板的序号
            if(strpos($a_sort, '#') !== false)$a_sort = str_replace("#", "", $a_sort);
            //正板（不带“#”），加上“#”就是背板的序号
            else $a_sort = "{$a_sort}#";

            $where = [
                ['g.order_id','=',$give_list[0]['order_id']],
                ['a.sort','=',$a_sort],
                ['g.counter','=',$give_list[0]['counter']],//取相同序号的产品
            ];
            $give2 = Db::name('mill_order_archives_give')
                ->alias('g')
                ->field('g.*,g.status as give_status,a.one_area')//,o.give_sort
                ->leftJoin('mill_order o','o.id=g.order_id')
                ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                ->where($where)
                ->find();

            if(!empty($give2)){
                $give2 = array_merge($give_list[0],$give2);

                $give_list[] = $give2;
            }

        }

        foreach ($give_list as $give){
            //发货状态，绑定车牌ID
            if($user['group'] == 8){
                //如果发货单号为空，则获取最近一个发货单号
                $address_sn = trim($address_sn);
                if(empty($address_sn))$address_sn = AddressModel::lastAddressSn($user['uid'],$give);
                $give['is_address'] = 1;
                $give['car_id'] = $car_id;
                $give['address_sn'] = $address_sn;
            }
            //------------补扫情况，自动补满之前所有状态-------------
            $sup_status = $user['give_sort'];//需要补充到的状态
            $save = GiveModel::giveToStatus($user,$sup_status,$give);
            $log_list = isset($save['log_list'])?$save['log_list']:'';

            $give['status'] = $save['status'];

            unset($save['log_list']);
            //----------补扫情况，自动补满之前所有状态 END----------

            //看是否还有质检不合格的工艺
            if($give['give_status']<0 && abs($give['give_status']) == $role[$user['group']]['status'][0]){

                //获取最后一条质检不合格的记录
                $status_q = '';
                $quality_flow_status = Db::name('mill_order_archives_give_quality')->where(['give_id'=>$give['id'],'quality_status'=>-1])->order('quality_time desc')->value('quality_flow_status');
                $quality_flow_status = explode(',',$quality_flow_status);
                if(!empty($quality_flow_status)){
                    foreach ($quality_flow_status as $fs){
                        if($fs > abs($give['status']))$status_q = $fs;
                    }
                }

                if(empty($status_q))$save['quality_status'] = 2;//质检，已返修
            }

            $give_where = ['id'=>$give['id']];
            //小件，批量处理
            if(!empty($give['part'])){
                $give_where = ['archives_id'=>$give['archives_id']];
                //获取所有小件的产品
                $part_list = Db::name('mill_order_archives_give')->where($give_where)->select();
                $new_log_list = [];
                foreach ($part_list as $pv){
                    //每个小件都生成对应的扫码记录
                    foreach ($log_list as $lv){
                        $lv['give_id'] = $pv['id'];
                        $lv['give_sn'] = $pv['give_sn'];
                        $lv['counter'] = $pv['counter'];

                        $new_log_list[] = $lv;
                    }
                }
                if(!empty($new_log_list))$log_list = $new_log_list;

            }
            if(Db::name('mill_order_archives_give')->where($give_where)->update($save)){

                //生成扫码记录
                GiveModel::addGiveLog($log_list,$uid_arr,$quality);
                //检查更新产品主体状态
                ArchivesModel::checkStatus($give['archives_id'],$user['give_sort']);

                //看是否需要更新至返工的质检工艺
                if(!empty($status_q))Db::name('mill_order_archives_give')->where($give_where)->update(['status'=>"-{$status_q}"]);

            }
        }


    }
    public function delGive(){

        $user = $this->member;

        //权限
        $role_status = isset(GiveModel::$role[$user['group']]['status'][0])?GiveModel::$role[$user['group']]['status'][0]:'';

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();
            if (empty($data['give_sn']))errors('请选择产品');

            $where = [
                ['give_sn','=',$data['give_sn']],
            ];
            $give  = Db::name('mill_order_archives_give')
                ->alias('g')
                ->field('g.*,g.status as give_status,a.one_area,a.model,o.mill_id,o.status as order_status,o.client_id,o.user_price_status,o.user_price_setting,o.give_scale,o.give_sort,o.quality_status as order_quality_status')
                ->leftJoin('mill_order o','o.id=g.order_id')
                ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                ->where($where)
                ->find();

            if(empty($give) || $give['status'] != $role_status)errors("该产品在[".GiveModel::$give_status_search[$give['status']]."]工艺，不能删除");

            //回滚至上一个状态
            $old_where = [
                ['give_sn','=',$data['give_sn']],
                ['status','<',$role_status],
            ];
            $role_status_old = Db::name('mill_order_archives_give_log')->where($old_where)->order('status desc,status_time desc')->value('status');

            $archives_id = $give['archives_id'];

            //------------补扫情况，自动补满之前所有状态-------------
            $sup_status = $role_status_old;//需要补充到的状态
            $save = GiveModel::giveToStatus($user,$sup_status,$give);
            $log_list = isset($save['log_list'])?$save['log_list']:'';

            //$give['status'] = $save['status'];

            unset($save['log_list']);
            //----------补扫情况，自动补满之前所有状态 END----------

            $give_where = ['id'=>$give['id']];
            if(Db::name('mill_order_archives_give')->where($give_where)->update($save)){

                //删除当前状态的扫码记录
                GiveModel::addGiveLog($log_list);

            }

            ArchivesModel::checkStatus($archives_id,$role_status);

            success('操作成功',[]);
        }

        errors('操作异常');

    }
    public function ableGive_old()
    {

        $role = GiveModel::$role;

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();

            $_log_time = time();
            $_log_i = 0;
            //file_put_contents('扫码.log',date('Y-m-d H:i:s',$_log_time)."  记数：{$_log_i}\r\n".json_encode($data,JSON_UNESCAPED_UNICODE)."\r\n\r\n",FILE_APPEND);

            //获取离线状态下的用户ID
            $archives_sn = !empty($data['archives_sn'])?$data['archives_sn']:'';
            $give_sn = explode(',',$data['give_sn']);
            $user_ids = !empty($data['uid'])?explode(',',$data['uid']):'';
            $car_ids = !empty($data['car_id'])?explode(',',$data['car_id']):'';
            $color_s = !empty($data['color'])?explode(',',$data['color']):'';
            $address_sn_s = !empty($data['address_sn'])?explode(',',$data['address_sn']):'';

            $user = $this->member;

            $data_list = [];
            if(!empty($give_sn)){
                $_log_str = '';
                foreach ($give_sn as $k=>$v){

                    $uid_arr = !empty($user_ids[$k])?$user_ids[$k]:$user['id'];
                    $uid_arr = explode('|',$uid_arr);//多人联合扫码，用“|”分隔，并按系统分配的比例工作量
                    $uid = $uid_arr[0];//默认第一个uid，为主扫码人
                    $car_id = !empty($car_ids[$k])?$car_ids[$k]:$car_ids;
                    $color = !empty($color_s[$k])?$color_s[$k]:$color_s;
                    $address_sn = !empty($address_sn_s[$k])?$address_sn_s[$k]:$address_sn_s;
                    $user = Db::name('admin_user')
                        ->alias('u')
                        ->field('u.*,u.id as uid,g.name as group_name,g.name as job_name')
                        //->leftJoin('admin_user_group g','g.id=u.group')
                        ->leftJoin('admin_user_job g','g.id=u.job')//不再显示部门，改成显示工位
                        ->where(['u.id'=>$uid])
                        ->find();

                    $where = [
                        ['g.give_sn','=',$v],
                    ];

                    //判断产品编号是否完整
                    if(strpos($v,'-') === false){

                        //匹配批次
                        if(!empty($archives_sn)){
                            $where = [
                                ['g.give_sn','like',"%-{$v}"],
                                ['g.archives_sn','=',$archives_sn],
                            ];
                        }
                        else {
                            $where = '1=2';
                            $msg = '请选择批次';
                        }
                    }

                    //成功的提示
                    $msg_succ = '成功';

                    $give = Db::name('mill_order_archives_give')
                        ->alias('g')
                        ->field('g.*,g.status as give_status,a.one_area,a.model,o.mill_id,o.status as order_status,o.is_process,o.client_id,o.user_price_status,o.user_price_setting,o.give_scale,o.quality_status as order_quality_status')//,o.give_sort
                        ->leftJoin('mill_order o','o.id=g.order_id')
                        ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                        ->where($where)
                        ->find();

                    if($give && $give['order_status'] > 0){
                        $time = time();
                        $status_flow = $give['status_flow'];
                        $group = $user['group'];
                        //补扫情况，自动补满之前所有状态
                        $sup = GiveModel::$sup;
                        if(!empty($sup[$user['group']]) && $give['status']<$sup[$user['group']]){
                            $sup_status = $sup[$user['group']];//需要补充到的状态
                            $status_flow_update = GiveModel::giveToStatus4($user,$status_flow,abs($give['status']),$sup_status,$give);

                            $give['status'] = $status_flow_update['status'];
                            $status_flow = $status_flow_update['status_flow'];

                            unset($status_flow_update['status']);
                            unset($status_flow_update['status_flow']);
                        }

                        if($give['give_status']<0 && abs($give['give_status']) == $role[$user['group']]['status'][0]){

                            //获取最后一条质检不合格的记录
                            $status_q = '';
                            $quality_flow_status = Db::name('mill_order_archives_give_quality')->where(['give_id'=>$give['id'],'quality_status'=>-1])->order('quality_time desc')->value('quality_flow_status');
                            $quality_flow_status = explode(',',$quality_flow_status);
                            if(!empty($quality_flow_status)){
                                foreach ($quality_flow_status as $fs){
                                    if($fs > abs($give['status']))$status_q = $fs;
                                }
                            }

                            $status = abs($give['status']);
                            if(empty($status_q))$status_flow_update['quality_status'] = 2;//质检，已返修
                            $field_time = "status{$status}_time";
                        }
                        else {
                            $status = $give['status']+1;
                            $status = GiveModel::roleMill($user,$status,$give['is_process']);
                            $field_time = "status{$status}_time";

                            if(!strpos($status_flow,"_{$status}|") !== false){
                                if($status_flow)$status_flow .= ",";
                                $status_flow .= "_{$status}|{$uid}_";
                            }
                            else $time = 0;
                        }
                        if($give['give_status']<0)$time = 0;

                        // 验证权限
                        $msg = GiveModel::role($user,$status);
                        //验证该产品是否已取消生产
                        if($give['quality_status'] == -3)$msg = '该产品已取消生产';
                        //单独验证发货部是否禁止发货
                        if($give['address_status'] < 0 && $user['group'] == 8)$msg = '该产品禁止发货';

                        //发货日志
                        if($user['group'] == 8)file_put_contents('扫码发货.log',date('Y-m-d H:i:s',$_log_time)."  档案号：{$give['archives_sn']}   编号：{$give['give_sn']}   扫码编号：{$v}\r\n".json_encode($data,JSON_UNESCAPED_UNICODE)."\r\n\r\n",FILE_APPEND);

                        //匹配批次
                        if(empty($msg) && $archives_sn && !in_array($give['archives_sn'],explode(',',$archives_sn))){
                            $msg = '批次不匹配';
                        }

                        //匹配折弯颜色
                        if(empty($msg) && $color){
                            $give_color = Db::name('mill_order_archives')->where(['id'=>$give['archives_id']])->value('color');
                            if($color != $give_color)$msg = '颜色不匹配';
                        }

                        //判断是否需要质检
                        $quality = [];//质检设置
                        if($give['order_quality_status'] == 1){
                            $quality_where = [
                                ['status','=',0],
                                ['order_id','=',$give['order_id']],
                                ['model','=',$give['model']],
                            ];
                            //质检设置
                            $quality = Db::name('mill_order_archives_quality_setting')->where($quality_where)->where([['give_status','=',$status]])->find();
                            //当前工艺是否首检：仅做语音提示
                            if(!empty($quality))$msg_succ .= "。[".GiveModel::$give_status[$status]."]工艺要首检";
                            //获取上个工艺未首检的状态
                            $quality_0 = Db::name('mill_order_archives_quality_setting')->where($quality_where)->where([['is_first','=',1],['give_status','<',$status]])->find();
                            //上个工艺是否首检：上个工艺未首检不让扫码
                            if(!empty($quality_0))$msg = "[".GiveModel::$give_status[$quality_0['give_status']]."]工艺未质检";
                        }
                        //质检问题的产品，需重新质检
                        if($give['quality_status'] < 0)$msg = "因质量问题，[".GiveModel::$give_status[abs($give['status'])]."]工艺请重新质检";

                        if(empty($msg) && !empty(GiveModel::$give_status[$status])){
                            $save = [
                                'status'                =>  $status,
                                'status_flow'           =>  $status_flow,
                                //'quality_flow_group'    =>  $group,
                                //$field_time             =>  $time,
                            ];
                            if(!empty($time))$save[$field_time] = $time;
                            if(!empty($status_flow_update))$save = array_merge($save,$status_flow_update);
                            //发货状态，绑定车牌ID
                            $address_status = GiveModel::$role[8]['status'][0];
                            if($field_time == "status{$address_status}_time" && !empty($car_id)){
                                //如果发货单号为空，则获取最近一个发货单号
                                $give['car_id'] = $car_id;
                                $address_sn = trim($address_sn);
                                if(empty($address_sn))$address_sn = AddressModel::lastAddressSn($uid,$give);
                                $save['car_id'] = $car_id;
                                $save['address_sn'] = $address_sn;
                            }
                            if(isset($give["status{$status}_sub"])){
                                $save = GiveModel::role_sub($user,$save,$give["status{$status}_sub"],$give['status']);
                            }

                            $give_where = ['id'=>$give['id']];
                            if(Db::name('mill_order_archives_give')->where($give_where)->update($save)){
                                //生成扫码记录
                                //扫码记录
                                $log = [
                                    'status'            =>  $status,
                                    'status_time'       =>  time(),
                                    'status_uid'        =>  $user['uid'],
                                    'mill_id'           =>  $user['mill_id'],
                                    'job_id'            =>  $user['job'],
                                    'job_name'          =>  empty($user['job_name'])?'':$user['job_name'],
                                    'group_id'          =>  empty($user['group_id'])?$user['group']:$user['group_id'],
                                    'give_id'           =>  $give['id'],
                                    'give_sn'           =>  $give['give_sn'],
                                    'order_id'          =>  $give['order_id'],
                                    'order_pid'         =>  $give['order_pid'],
                                    'client_id'         =>  $give['client_id'],
                                    'archives_id'       =>  $give['archives_id'],
                                    'archives_sn'       =>  $give['archives_sn'],
                                    'one_area'          =>  $give['one_area'],
                                    'counter'           =>  $give['counter'],
                                    'model_type'        =>  $give['model_type'],
                                    //员工单价设置
                                    'give_scale'        =>  $give['give_scale'],
                                    'user_price_status' =>  $give['user_price_status'],
                                    'user_price_setting'=>  $give['user_price_setting'],

                                ];
                                //发货
                                if($field_time == "status{$address_status}_time" && !empty($car_id)){
                                    $log['car_id'] = $save['car_id'];
                                    $log['address_sn'] = $save['address_sn'];
                                    $log['address_date'] = $save['address_date'];
                                    $log['address_time'] = $save['address_time'];
                                    $log['address_status'] = $save['address_status'];
                                }

                                //生成扫码记录
                                GiveModel::addGiveLog($log,$uid_arr,$quality);
                                //检查更新产品主体状态
                                ArchivesModel::checkStatus($give['archives_id'],$status);

                                //看是否需要更新至返工的质检工艺
                                if(!empty($status_q))Db::name('mill_order_archives_give')->where($give_where)->update(['status'=>"-{$status_q}"]);

                            }
                        }

                        $give = Db::name('mill_order_archives_give')
                            ->alias('g')
                            ->field("a.*,o.batch,o.engineering,g.status as give_status,g.give_sn,g.archives_sn,g.counter,concat(g.counter,'/',a.number) as number_str")
                            ->leftJoin('mill_order o','o.id=g.order_id')
                            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                            ->where(['g.id'=>$give['id']])
                            ->find();
                    }
                    else{
                        if(empty($msg))$msg = '该产品不存在';
                        $give['give_sn'] = $v;

                    }

                    if(!empty($give['sort']))$give['sort'] = "{$give['sort']}-{$give['counter']}";
                    //1：成功 0：失败
                    $give['status_code'] = empty($msg)?1:0;
                    $give['nickname'] = $user['nickname'];
                    $give['group_name'] = $user['group_name'];
                    //提示状态
                    $give['code_str'] = '该产品不存在';
                    if(isset($give['give_status']))$give['code_str'] = GiveModel::$give_status[$give['give_status']];

                    $give['status_str'] = $msg?$msg:'已上传';
                    //成功的提示
                    $give['msg'] = $msg_succ;

                    $give['time_str'] = date('Y.m.d H:i');

                    $data_list[] = $give;

                    $_log_str .= "产品编号：{$give['give_sn']}  状态：{$give['status_str']}";
                }

                //file_put_contents('扫码reust.log',date('Y-m-d H:i:s',$_log_time)."  记数：{$_log_i}\r\n".$_log_str."\r\n\r\n",FILE_APPEND);

                success('操作成功',$data_list);
            }
            errors('操作失败');
        }

        errors('操作异常');
    }
    /**
     * 分配发货单号
     */
    public function addressSn(){

        success('操作成功',['address_sn'=>GiveModel::getAddressSn()]);
    }
    /**
     * 确认发货
     * @return mixed
     */
    public function carGive()
    {

        //发货状态
        $status = GiveModel::$role[8]['status'][0];
        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();
            if (!isset($data['address_sn']))$data['address_sn'] = '';
            if (!isset($data['give_sn']))$data['give_sn'] = '';
            if (!isset($data['car_id']))$data['car_id'] = '';

            $address_sn_s = unique($data['address_sn']);

            //按批次分组
            $where = [
                ['address_sn','=',$address_sn_s],
                //['status','=',$status],
                ['address_status','=',0],

            ];
            $archives_ids = '';
            $give_list = Db::name('mill_order_archives_give')
                //->field('address_sn,order_id,order_pid,archives_sn,GROUP_CONCAT(DISTINCT id) as give_ids,GROUP_CONCAT(DISTINCT archives_id) as archives_ids')
                ->field('address_sn,order_id,order_pid,archives_sn')
                ->where($where)
                ->group('address_sn,order_id')
                ->select();

            $user = $this->member;

            //权限
            //$role_status = isset(GiveModel::$role[$user['group']]['status'][0])?GiveModel::$role[$user['group']]['status'][0]:'';

            $data_list = [];
            if(!empty($give_list)){

                $time = time();

                foreach ($give_list as $v){

                    //$archives_ids .= ",{$v['archives_ids']}";
                    //分配发货单号
                    if(strpos($address_sn_s,$v['address_sn']) !== false){
                        $address_sn = $v['address_sn'];
                        $address_sn_s = str_replace($v['address_sn'],"",$address_sn_s);
                    }
                    else $address_sn = GiveModel::getAddressSn($time);

                    // 验证权限
                    $msg = '';

                    $save = [
                        'address_status'        =>  1,
                        'address_date'          =>  date('Y-m-d',$time),
                        'address_time'          =>  $time,
                        'address_sn'            =>  $address_sn,
                    ];

                    //$give_where = [['id','in',$v['give_ids']]];
                    $give_where = [['address_sn','=',$v['address_sn']],['order_id','=',$v['order_id']]];
                    $up_log = Db::name('mill_order_archives_give')->where($give_where)->update($save);

                    $give_log_where = [['address_sn','=',$v['address_sn']],['order_id','=',$v['order_id']]];
                    $up_log2 = Db::name('mill_order_archives_give_log')->where($give_log_where)->update($save);

                    ////1：成功 0：失败
                    ////$give['status_code'] = empty($msg)?1:0;
                    //$give['status_code'] = 1;
                    //$give['nickname'] = $user['nickname'];
                    //$give['group_name'] = $user['group_name'];
                    ////提示状态
                    //$give['code_str'] = '';
                    //$give['status_str'] = $msg?$msg:'已上传';
                    //$give['status_str'] = '已上传';
                    //$give['time_str'] = date('Y.m.d H:i');

                    //$data_list[] = $give;
                }

                //检查更新产品主体状态
                //if(!empty($archives_ids)){
                //    $archives_ids = explode(',',trim($archives_ids,','));
                //    foreach ($archives_ids as $archives_id){
                //        ArchivesModel::checkStatus($archives_id,$status);
                //    }
                //
                //}
                success('操作成功',[]);
            }
            success('后台已确认装车',[]);
        }


        errors('操作异常');
    }
    /**
     * 扫码质检产品状态
     * @return mixed
     */
    public function qualityStatus(){

        $status_list = GiveModel::$give_status_search;
        unset($status_list[0]);

        $list = [];
        foreach ($status_list as $k=>$v){
            $list[] = [
                'id'        =>  $k,
                'title'     =>  $v,
            ];
        }

        success('', array('list' => $list, 'pagesize' => 999, 'total' => 999, 'pindex' => 999, 'total_pages' => 1));
    }
    /**
     * 扫码质检产品质量原因
     * @return mixed
     */
    public function qualityReason(){

        $quality_reason_list = config('mill_give_quality_reason');

        $list = [];
        foreach ($quality_reason_list as $k=>$v){
            $list[] = [
                'id'        =>  $k,
                'title'     =>  $v,
            ];
        }

        success('', array('list' => $list, 'pagesize' => 999, 'total' => 999, 'pindex' => 999, 'total_pages' => 1));
    }
    /**
     * 扫码质检产品
     * @return mixed
     */
    public function quality(){

        //file_put_contents('质检.log'.json_encode(input(),JSON_UNESCAPED_UNICODE)."\r\n\r\n",FILE_APPEND);

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();
            if(empty($data['status']))$data['status'] = 0;

            //责任环节改为多选
            if(empty($data['give_status']) && $data['status'] < 0)errors('请选择责任环节',['status_code'=>0,'status_str'=>'请选择责任环节']);
            //质量原因    多选
            if(empty($data['reason']) && $data['status'] < 0)errors('请选择质量原因',['status_code'=>0,'status_str'=>'请选择质量原因']);

            $user = $this->member;

            //质检
            $re = GiveModel::quality($user,$data);

            if($re){
                $give = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field("a.*,o.batch,o.engineering,g.give_sn,g.archives_sn,g.quality_status,g.counter,g.status as give_status,concat(g.counter,'/',a.number) as number_str")
                    ->leftJoin('mill_order o','o.id=g.order_id')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where([['g.give_sn','in',$data['give_sn']]])
                    ->find();

                $give['nickname'] = $user['nickname'];
                $give['group_name'] = $user['group_name'];

                //提示状态
                $give['code_str'] = GiveModel::$give_status[abs($give['give_status'])].GiveModel::$quality_status[$give['quality_status']];
                if(!empty($give['sort']))$give['sort'] = "{$give['sort']}-{$give['counter']}";
                $give['status_code'] = 1;
                $give['status_str'] = '已上传';
                $give['time_str'] = date('Y.m.d H:i');

                success('操作成功',$give);
            }
            if(empty($re))$re = '';
            errors($re,['status_code'=>0,'status_str'=>$re]);
        }

        errors('操作异常');
    }
    /**
     * 车牌列表
     */
    public function carList(){
        $user = $this->member;

        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $role_status = GiveModel::$role[$user['group']];

        $where = ['status'=>1];
        $order = 'id desc';

        $list = Db::name('mill_car')
            ->where($where)
            ->order($order)
            //->limit((($pindex-1)*$psize),$psize)
            ->select();

        $total = Db::name('mill_car')
            ->where($where)
            ->count();

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
        //success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => max(1,ceil($total/$psize))));
    }
    /**
     * 历史记录
     */
    public function giveList(){
        $user = $this->member;

        $sub_status = input('sub_status');
        $pindex = max(1, intval(input('page',1)));
        $psize = 30;

        $role_status = GiveModel::$role[$user['group']];

        $where = [];
        $order = '';

        //质检部
        if(isset($role_status['quality'])){

            $where[] = ['g.quality_uid','=',$user['uid']];
            $order .= 'g.quality_time desc';
        }
        //其他部门
        else{
            $where[] = ["g.is_bu",'=',0];
            $where[] = ['g.status_uid','=',$user['uid']];
            //排序
            foreach ($role_status as $field=>$val){
                if(is_array($val)){
                    foreach ($val as $v){
                        if($field == 'color' || $field == 'sub')continue;
                        if($v === true)$v = '';
                        $order .= "g.{$field}_time desc,";
                    }
                }
            }
        }

        $order = trim($order,',');
        /*$list = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field("a.*,o.batch,o.engineering,g.status as give_status,g.id as give_id,g.give_sn,g.archives_sn,g.status_flow,g.status1_time,g.status2_time,g.status3_time,g.status4_time,g.quality_time,g.quality_status,g.counter,concat(g.counter,'/',a.number) as number_str")
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where($where)
            ->order($order)
            ->limit((($pindex-1)*$psize),$psize)
            ->select();*/
        $order_ids = Db::name('mill_order_archives_give_log')
            ->alias('g')
            ->where($where)
            ->order($order)
            ->limit((($pindex-1)*$psize),$psize)
            ->column("DISTINCT g.order_id");
        $list = [];

        if(!empty($order_ids)){
            foreach ($order_ids as $order_id){

                $give_where = $where;
                $give_where[] = ['g.order_id','=',$order_id];
                $give = Db::name('mill_order_archives_give_log')
                    ->alias('g')
                    ->field("o.*,g.status_flow,g.status1_time,g.status_time,g.quality_time,g.quality_status")
                    ->leftJoin('mill_order o','o.id=g.order_id')
                    ->where($give_where)
                    ->order($order)
                    ->find();
                $give['order_sn'] = $give['archives_sn'];

                //质检部
                if(isset($role_status['quality'])){

                    $field_time = "quality_time";
                }
                //其他部门
                else{

                    $field_time = "status_time";
                }

                $give['time_str'] = date('Y.m.d H:i',$give[$field_time]);

                //总数量
                $give['archives_sum'] = Db::name('mill_order_archives')
                    ->where(['order_id'=>$order_id])
                    ->sum("number");
                //已扫总数量
                $give['status_sum'] = Db::name('mill_order_archives_give_log')
                    ->alias('g')
                    ->where("g.order_id = {$order_id} and g.status != 0")
                    ->count("DISTINCT g.id");
                //当前账号已扫数量
                $give['number'] = Db::name('mill_order_archives_give_log')
                    ->alias('g')
                    ->where($give_where)
                    ->count("DISTINCT g.id");

                $list[] = $give;
            }
        }

        $total = Db::name('mill_order_archives_give_log')
            ->alias('g')
            ->where($where)
            ->order($order)
            ->count("DISTINCT g.order_id");

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => max(1,ceil($total/$psize))));
    }
    /**
     * 员工列表
     */
    public function userList(){
        $user = $this->member;

        $uid = input('uid');
        //判断是不是扫的员工码
        if(empty($uid) || strpos($uid,'user') === false)errors('请扫描员工码');
        $uid = str_replace('user',"","{$user['uid']}|{$uid}");//将登录账号设为主扫码人
        $uid_arr = explode('|',$uid);
        $uid_arr = array_unique($uid_arr);//去掉重复的UID
        $uids = '';//员工UID合集，用于返给前端，排除不存在或被禁用的员工UID

        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        //$role_status = GiveModel::$role[$user['group']];

        $give_scale_name = GiveModel::$give_scale_name;
        $list = [];
        $msg = '';
        foreach ($uid_arr as $uk=>$uid){
            $where = [['id','=',$uid]];
            $u_user = Db::name('admin_user')->field('id,nickname,group,status')->where($where)->find();
            if(empty($u_user) || $u_user['status']  = 0 || $u_user['delete'] = 0){
                if(empty($u_user))$msg = '该员工码不存在';
                else $msg = "{$u_user['nickname']}已被禁用，请联系管理员";
                errors($msg);
            }
            //if($u_user['group'] != $user['group'])errors("{$u_user['nickname']}不在{$user['group_name']}部");

            $uids .= "|{$uid}";//员工UID合集
            $u_user['nickname'] = $give_scale_name[($uk+1)]."：".$u_user['nickname'];
            $list[] = $u_user;
        }
        $uids = trim($uids,'|');

        if(!empty($list)){
            foreach ($list as &$v){
                $v['uids'] = $uids;//给每个员工列表都加入员工UID合集
            }
        }

        $total = count($list);

        success($msg, array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
        //success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => max(1,ceil($total/$psize))));
    }
    /**
     * 批次列表
     */
    public function batchList(){
        $user = $this->member;

        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $role_status = GiveModel::$role[$user['group']];
        //发货前的最后一个状态
        $address_status = GiveModel::$role[8]['status'][1];

        $archives_sn = input('archives_sn');
        $archives_sn = str_replace('，',',',strtoupper($archives_sn));
        $archives_sn_arr = explode(',',$archives_sn);
        $where_sn = '';
        if(!empty($archives_sn_arr) && !empty($archives_sn)){
            foreach ($archives_sn_arr as $sn){
                if(!empty($where_sn))$where_sn .= ' OR ';
                $where_sn .= " o.archives_sn like '%{$sn}%'";
            }
        }

        $where = [['o.status','=',1],['g.status','<',$address_status]];
        $order = 'o.status_time desc,o.id desc';

        $list = Db::name('mill_order')
            ->field("o.id,o.archives_sn,o.batch,concat(o.archives_sn,'/',o.batch) as batch_str")
            ->alias('o')
            ->leftJoin('mill_order_archives_give g','g.order_id=o.id')
            ->where($where)
            ->where($where_sn)
            ->group('o.id')
            ->order($order)
            //->limit((($pindex-1)*$psize),$psize)
            ->select();

        $total = count($list);

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
        //success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => max(1,ceil($total/$psize))));
    }
    /**
     * 颜色列表
     */
    public function colorList(){
        $user = $this->member;

        $archives_sn = input('archives_sn');
        if(empty($archives_sn))errors('请选择批次');
        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $role_status = GiveModel::$role[$user['group']];

        $where = [['archives_sn','in',$archives_sn]];
        $order = 'id asc';

        $list = Db::name('mill_order_archives')
            ->field("distinct color")
            ->where($where)
            ->order($order)
            //->limit((($pindex-1)*$psize),$psize)
            ->select();

        $total = Db::name('mill_order')
            ->where($where)
            ->count();

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
        //success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => max(1,ceil($total/$psize))));
    }
    /**
     * 产品列表
     */
    public function archivesGiveList(){
        $user = $this->member;

        $archives_sn = input('archives_sn');
        $give_sn = input('give_sn');
        if(empty($archives_sn))errors('请选择批次');
        if(empty($give_sn))errors('请输入产品编号');
        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $role_status = GiveModel::$role[$user['group']];

        $list = [];

        $give_sn = explode(',',$give_sn);
        foreach ($give_sn as $k=>$v){

            $where[] = ['g.give_sn','=',$v];

            //判断产品编号是否完整
            if(strpos($v,'-') === false){

                $where = [
                    ['g.give_sn','like',"%-{$v}"],
                ];
            }
            $where[] = ['g.archives_sn','=',$archives_sn];

            $give = Db::name('mill_order_archives_give')
                ->alias('g')
                ->field("a.*,o.batch,g.status as give_status,g.give_sn,g.archives_sn,g.counter,concat(g.counter,'/',a.number) as number_str")
                ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                ->leftJoin('mill_order o','o.id=g.order_id')
                ->where($where)
                ->find();

            if($give){
                if(!empty($give['sort']))$give['sort'] = "{$give['sort']}-{$give['counter']}";
                $give['status_str'] = GiveModel::$give_status[$give['give_status']];

                $list[] = $give;
            }

        }

        $total = 99999;

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
        //success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => max(1,ceil($total/$psize))));
    }
    //批次发货情况统计
    public function carBatchStat(){

        $tb_status = GiveModel::$role[12]['status'][0];//复合状态

        $user = $this->member;
        $user['give_sort'] = GiveModel::$role[$user['group']]['status'][0];
        $status = $user['give_sort'];

        $archives_sn = input('archives_sn');
        $color = input('color');
        $car_id = input('car_id');
        $address_sn = input('address_sn');
        if(empty($archives_sn))errors('请选择批次');
        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $archives_sn_arr = explode(',',$archives_sn);
        $list = [];
        foreach ($archives_sn_arr as $sn){

            $order = Db::name('mill_order')->where([['archives_sn','=',$sn]])->find();

            $stat['engineering'] = $order['engineering'];
            //$stat['archives_sn'] = $order['archives_sn'];
            $stat['archives_sn'] = $order['batch'];
            $stat['batch'] = $order['batch'];
            $stat['color'] = $color;
            //总数量
            $stat_where = [['a.order_id','=',$order['id']]];
            if($color)$stat_where[] = ['a.color','=',$color];
            if($status >= $tb_status)$stat_where[] = ['a.is_process','=',0];
            $stat['give_sum'] = Db::name('mill_order_archives')
                ->alias('a')
                ->where($stat_where)
                ->sum('a.number');

            $status_str = GiveModel::$give_status[$status];
            //已扫码数量
            $stat_where = [
                ['g.order_id','=',$order['id']],
                ['g.status','=',$status],
                ['g.is_last','=',1],
            ];
            if($status >= $tb_status)$stat_where[] = ['a.is_process','=',0];
            //焊接
            if($color){
                //已焊接数量
                $stat_where[] = ['a.color','=',$color];
                $stat['ok_sum'] = Db::name('mill_order_archives_give_log')
                    ->alias('g')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($stat_where)
                    ->count();
            }
            //开料，折弯，发货
            else $stat['ok_sum'] = Db::name('mill_order_archives_give_log')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($stat_where)->count();

            $stat['status_str'] = "总数:{$stat['give_sum']}/已{$status_str}:{$stat['ok_sum']}/未{$status_str}:".($stat['give_sum']-$stat['ok_sum']);

            //扫码人情况
            if($user['group'] == 8){

                //喷涂状态
                $status2 = GiveModel::$role[7]['status'][0];
                //已喷涂数量
                $stat_where2 = [
                    ['g.order_id','=',$order['id']],
                    ['g.status','=',$status2],
                    ['g.is_last','=',1],
                ];
                if($status >= $tb_status)$stat_where[] = ['a.is_process','=',0];
                $stat['user_ok_sum2'] = Db::name('mill_order_archives_give_log')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($stat_where2)->count();

                $stat_where[] = ['g.status_uid','=',$user['uid']];
                if($car_id)$stat_where[] = ['g.car_id','=',$car_id];
                if($address_sn)$stat_where[] = ['g.address_sn','=',$address_sn];

                $stat['user_ok_sum'] = Db::name('mill_order_archives_give_log')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($stat_where)->count();

                $stat['status_str'] = "已喷涂:{$stat['user_ok_sum2']}/当车已扫:{$stat['user_ok_sum']}/未{$status_str}:".($stat['give_sum']-$stat['ok_sum']);
            }

            $list[] = $stat;
        }

        $total = count($archives_sn_arr);

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
    }
    /**
     * 新增车牌号
     */
    public function addCar(){

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();
            $rule = [
                'plate_number|车牌号' => 'require',
            ];
            if(($message =$this->validate($data,$rule)) !== true)errors([],$message);

            //函数:SBC_DBC  中文标点转英文标点
            //函数:replaceSpecialChar  去除所有标点字符包括空格
            //函数:strtoupper  转大写
            $data['plate_number'] = filterStr($data['plate_number']);
            $update = [
                'plate_number'  =>  $data['plate_number'],
            ];
            $count = Db::name('mill_car')->where($update)->count();
            if($count > 0)errors('该车牌号已存在');
            $re = Db::name('mill_car')->insert($update);

            if(!empty($re))success('提交成功');
            errors('提交失败,请重试');

        }

    }
    /**
     * 确认产品进度
     * @return mixed
     */
    public function subGive()
    {

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();

            $archives_sn_s = unique($data['archives_sn']);

            $user = $this->member;
            $role_status = GiveModel::$role[$user['group']]['status'][0];

            //按批次分组
            $where = [
                ['archives_sn','in',$archives_sn_s],
                ["status{$role_status}_sub",'=',1],
                ['status_flow','like',"%\\_{$role_status}|{$user['uid']}\\_%"],

            ];

            $save = [
                'status'                             =>  $role_status,
                "status{$role_status}_sub"           =>  2,
                "status{$role_status}_time"          =>  time(),
            ];

            //Db::name('mill_order_archives_give')->where($where)->select();
            Db::name('mill_order_archives_give')->where($where)->update($save);

            success('操作成功',[]);
        }

        errors('操作异常');
    }

    public function test(){

        /*//粉末
        $add_a = [
            'create_time'       =>  time(),
            'type_pid'          =>  12,
            'type_id'           =>  14,
            'supplier_id'       =>  1,
            'heat'              =>  0,
            'color_type_id'     =>  5,
        ];

        $full_path = 'D:/office/phpstudy_pro/WWW/xjp/public/uploads/fenmo.xls';

        //外购油漆
        $add_a = [
            'create_time'       =>  time(),
            'type_pid'          =>  1,
            'type_id'           =>  13,
            'supplier_id'       =>  1,
            'heat'              =>  0,
            'color_type_id'     =>  1,
        ];

        $full_path = 'D:/office/phpstudy_pro/WWW/xjp/public/uploads/wgyq.xls';*/

        //自制油漆
        $add_a = [
            'create_time'       =>  time(),
            'type_pid'          =>  1,
            'type_id'           =>  24,
            'supplier_id'       =>  1,
            'heat'              =>  0,
            'color_type_id'     =>  1,
        ];

        $full_path = 'D:/office/phpstudy_pro/WWW/xjp/public/uploads/zzyq.xls';

        $archives_table = [
            'sheet'         =>  '即时库存',
            'rowStart'      =>  2,
            //'rowEnd'        =>  5,
            'table'         =>  'order_archives',
            'fields'        =>  [
                'B'         =>  'supplier_color',
                'C'         =>  'title',
                'G'         =>  'number',
            ],
        ];
        $sheet_read_arr = [$archives_table];
        $import = plugin_action('Excel/Excel/importarchives', [$full_path,$sheet_read_arr]);

        foreach ($import['order_archives']['lists'] as $v){
            $add = array_merge($add_a,$v);

            //如果没有名称，则只获取色号里的中文作为名称
            if(empty($add['title'])){
                preg_match_all("/[\x{4e00}-\x{9fa5}]+/u", $add['supplier_color'], $matches);
                $add['title'] = $matches[0][0];
            }
            $add['supplier_color'] = strtoupper(trim($add['supplier_color']));
            $add['model'] = $add['supplier_color'];
            //生成自编码
            $add['color_sn'] = ColorModel::getColorSn($add['type_id'],$add['heat']);

            //判断是否已录入
            $in_sn = StockModel::getStockSn($add,false);

            if(!empty($in_sn))continue;

            $re = StockModel::getStockSn($add);
            Db::name('wh_stock')->where(['stock_sn'=>$re])->update(['number'=>$add['number']]);

        }
    }
    public function test1(){
        /*['linkage:12||||must', 'type_pid', '物料类别', '', $type_plist,'', url('getStockType'), 'type_id'],
                ['linkage:12||||must', 'type_id', '类别', '', $type_list,'', url('getStockType'), 'type_id2'],
                //['linkage:12||||must', 'type_id2', '类别2', '', $type_list2,'', url('getStockType'), 'type_id3'],
                //['select:12||||must', 'type_id3', '类别3', '', $type_list3],
                ['text:12||||must', 'title', '库存名称'],
                ['select:12||||must', 'supplier_id', '供应商', '', $supplier,''],
                ['text:12||||must', 'supplier_color', '厂家色号'],
                ['select:12||||must', 'heat', '油温', '', MaterialModel::$heat,''],
                ['select:12||||must', 'color_type_id', '油漆类型', '', ColorModel::getColorType(),''],
                ['text:12||||must', 'model', '规格型号'],
                ['select:12||||must', 'quality', '材质', '', ColorModel::getQuality($info['type_pid'])],
                ['text:12||||must', 'lot_sn', '批号'],
                ['text:12||||must', 'thickness', '厚度'],
                ['text:12||||must', 'long', '长'],
                ['text:12||||must', 'high', '宽'],
                ['number:12||||must', 'number', '库存'],
                ['number:12||||must', 'num', '重量'],
                ['image:12||||must', 'img', '色卡'],*/


        //铝卷
        $add_a = [
            'create_time'       =>  time(),
            'type_pid'          =>  4,
            'supplier_id'       =>  1,
            'heat'              =>  0,
            'color_type_id'     =>  1,
        ];

        $full_path = 'D:/office/phpstudy_pro/WWW/xjp/public/uploads/lj.xls';

        $archives_table = [
            'sheet'         =>  'Sheet1',
            'rowStart'      =>  5,
            //'rowEnd'        =>  5,
            'table'         =>  'order_archives',
            'fields'        =>  [
                'E'         =>  'supplier_title',
                'F'         =>  'supplier_quality',
                'H'         =>  'thickness',
                'I'         =>  'model',
                'M'         =>  'number',
                'N'         =>  'lot_sn',
            ],
        ];
        $sheet_read_arr = [$archives_table];
        $import = plugin_action('Excel/Excel/importarchives', [$full_path,$sheet_read_arr]);

        foreach ($import['order_archives']['lists'] as $v){
            $add = array_merge($add_a,$v);

            $add['lot_sn'] = str_replace("卷号:", "", $add['lot_sn']);

            $add['title'] = '铝卷';
            $add['model2'] = $add['lot_sn'];
            $add['high'] = $add['model'];

            //录入供应商
            $supplier_title = $add['supplier_title'];
            unset($add['supplier_title']);
            $supplier_id = Db::name('wh_supplier')->where(['title'=>$supplier_title])->value('id');
            if(empty($supplier_id)){
                $supplier_add = [
                    'type_pid'          =>  $add['type_pid'],
                    'title'             =>  $supplier_title,
                    'title_abb'         =>  $supplier_title,
                    'sort'              =>  100,
                    'create_time'       =>  time(),
                    'update_time'       =>  time(),
                ];
                $supplier_id = Db::name('wh_supplier')->insertGetId($supplier_add);
            }
            $add['supplier_id'] = $supplier_id;

            //录入材质
            $supplier_quality = $add['supplier_quality'];
            unset($add['supplier_quality']);
            $quality_id = Db::name('wh_supplier_quality')->where(['title'=>$supplier_quality])->value('id');
            if(empty($quality_id)){
                $quality_add = [
                    'type_pid'          =>  $add['type_pid'],
                    'title'             =>  $supplier_quality,
                ];
                $quality_id = Db::name('wh_supplier_quality')->insertGetId($quality_add);
            }
            $add['quality'] = $quality_id;

            //铝卷系列
            if($add['thickness'] < 1)$add['type_id'] = 27;//0系
            elseif($add['thickness'] < 2)$add['type_id'] = 16;//1系
            elseif($add['thickness'] < 3)$add['type_id'] = 25;//2系
            elseif($add['thickness'] < 4)$add['type_id'] = 26;//3系

            //判断是否已录入
            $in_sn = StockModel::getStockSn($add,false);

            if(!empty($in_sn))continue;

            $re = StockModel::getStockSn($add);
            Db::name('wh_stock')->where(['stock_sn'=>$re])->update(['number'=>$add['number']]);

        }
    }


}
